package com.auto.survey.activity.bluetooth
import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.annotation.RequiresPermission
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.base.BaseActivity
import com.auto.survey.util.Helper
import com.auto.survey.widget.CentreToast
import com.auto.survey.widget.CommonTitle.Companion.TEXT_POSITON_RIGHT
import com.didi.davinci.switcher.UISwitcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 蓝牙页面
 */
class BluetoolsActivity : BaseActivity() {
    private val TAG = BluetoolsActivity::class.simpleName
    private lateinit var tvConnectStat:TextView
    private lateinit var switcher:UISwitcher
    private lateinit var rvSearch: RecyclerView
    private lateinit var rvConnected: RecyclerView
    private lateinit var searchAdapter: BluetoothDeviceAdapter
    private lateinit var pairedDevicesAdapter: BluetoothDeviceAdapter
    private lateinit var progress:ProgressBar

    private val scanList = mutableListOf<BluetoothDevice>()
    private val pairList = mutableListOf<BluetoothDevice>()

    private val bluetoothManager by lazy {
        BluetoothManagerUtil.getInstance(this)
    }

    companion object {
        private const val REQUEST_ENABLE_BT = 1
        const val EXTRA_DEVICE_ADDRESS = "EXTRA_DEVICE_ADDRESS"
    }

    // 广播接收器（仅处理经典蓝牙事件）
    private val bluetoothReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when (action) {
                BluetoothAdapter.ACTION_STATE_CHANGED -> {
                    val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
                    if (state == BluetoothAdapter.STATE_ON) {
                        bluetoothManager.fetchPairedDevices()
                    }
                }
                BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    device?.let {
                        bluetoothManager.updateBondState(it)
                        if (it.bondState == BluetoothDevice.BOND_NONE) {
                            tvConnectStat.text = "匹配失败"
                        }

                        if (it.bondState == BluetoothDevice.BOND_BONDING) {
                            tvConnectStat.text = "正在匹配"
                        }

                        if (it.bondState == BluetoothDevice.BOND_BONDED) {
                            tvConnectStat.text = "匹配成功"
                        }
                    }

                }
                BluetoothDevice.ACTION_ACL_CONNECTED -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    Log.i("BluetoothService", "===bluetoothReceiver===ACTION_ACL_CONNECTED=== device = $device")

                    if (device != null && device.bondState == BluetoothDevice.BOND_BONDED) {
                        tvConnectStat.text= "已连接设备:${device?.name} mac:${device?.address}"
                    }

//                    device?.let { addConnectedDevice(it) }
                }
                BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    Log.i("BluetoothService", "===bluetoothReceiver===ACTION_ACL_DISCONNECTED=== device = $device")
                    if (device != null && device.bondState == BluetoothDevice.BOND_BONDED) {
                        tvConnectStat.text= "${device?.name} mac:${device?.address}已断开设备连接"
                    }

//                    device?.let { removeConnectedDevice(it) }
                }
            }
        }
    }

    private val connectionCallback = object : BluetoothService.ConnectionCallback{
        override fun onDiscoverDeviceState(isdiscovery: Boolean) {
            if (isdiscovery) {
                progress.visibility = View.VISIBLE
            } else {
                progress.visibility = View.GONE



            }

        }

        override fun onConnectionStateChanged(device: BluetoothDevice, state: BluetoothService.ConnectionState) {
            Log.i(TAG, "===onConnectionStateChanged=== device = $device, state =$state")
            if (state == BluetoothService.ConnectionState.DISCONNECTED) {
                tvConnectStat.text= "连接${device.name}失败"
            }

            if (state == BluetoothService.ConnectionState.CONNECTING) {
                tvConnectStat.text= "正在连接设备中"
            }

            if (state == BluetoothService.ConnectionState.CONNECTED) {
                tvConnectStat.text= "已连接设备:${device?.name} mac:${device?.address}"
            }

            if (state == BluetoothService.ConnectionState.DISCONNECTING) {
                tvConnectStat.text= "${device?.name} mac:${device?.address}已断开设备连接"
            }

        }

        override fun onDataReceived(device: BluetoothDevice, data: ByteArray) {
            Log.i(TAG, "===onDataReceived===")
        }

        override fun onError(message: String) {
            Log.i(TAG, "===onError=== $message")
        }

    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    override fun initView() {
        // 绑定Service
        bluetoothManager.bindService()
        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.blue)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.blue)
        mComment_title?.setTitle("蓝牙连接")

        mComment_title?.setRightTitle("刷新蓝牙")
        mComment_title?.setTitleColor(Color.WHITE, TEXT_POSITON_RIGHT)
        mComment_title?.setOnRightTextClickListener(Helper.debounce{
            refreshBluetooth()
        })

        progress = findViewById(R.id.scan_progress)
        tvConnectStat = findViewById(R.id.tv_blueconnect)

        if (bluetoothManager.isBluetoothConnected()) {
            tvConnectStat.text= "已连接"
        } else {
            tvConnectStat.text= "未连接"
        }


        switcher = findViewById(R.id.blueSwitcher)
        switcher.setOnCheckedChangeListener {buttonView, isChecked->
            if (isChecked) {
                bluetoothManager.enableBluetooth(this, REQUEST_ENABLE_BT)
            } else {

                bluetoothManager.disableBluetooth(this@BluetoolsActivity)
            }
        }

        rvSearch = findViewById(R.id.rv_search_dev)
        rvConnected = findViewById(R.id.rv_connected_dev)

        // 初始化适配器
        searchAdapter = BluetoothDeviceAdapter(mutableListOf()) { bluetoothDeviceItem , position->

            if (bluetoothManager.getConnectedDevices2().contains(bluetoothDeviceItem)) {
                CentreToast.instance.showText("当前设备已经连接蓝牙")
            } else {

                bluetoothManager.connectDevice(bluetoothDeviceItem)
//                if(bluetoothManager.disAllConnectedDevice() == true){
//                    bluetoothManager.connectDevice(bluetoothDeviceItem)
//                }else {
////                    tvConnectStat.text = "关闭当前设备${bluetoothManager.getConnectedDevices2().get(0).name}连接失败"
//                }

            }

        }

        pairedDevicesAdapter = BluetoothDeviceAdapter(mutableListOf()) { bluetoothDeviceItem, position->
            if (bluetoothManager.getConnectedDevices2().contains(bluetoothDeviceItem)) {
                CentreToast.instance.showText("当前设备已经连接蓝牙")
            } else {
                bluetoothManager.connectDevice(bluetoothDeviceItem)
//                if(bluetoothManager.disAllConnectedDevice() == true){
//                    bluetoothManager.connectDevice(bluetoothDeviceItem)
//                } else {
////                    tvConnectStat.text = "关闭当前设备${bluetoothManager.getConnectedDevices2().get(0).name}连接失败"
//                }
            }
        }

        // 设置RecyclerView
        rvSearch.layoutManager = LinearLayoutManager(this)
        rvSearch.adapter = searchAdapter

        rvConnected.layoutManager = LinearLayoutManager(this)
        rvConnected.adapter = pairedDevicesAdapter


        registerReceiver(bluetoothReceiver, IntentFilter().apply {
            addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
            addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
            addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
            addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        })

        // 设置扫描回调（使用过滤后的设备列表）
        bluetoothManager.setScanCallback { filteredDevices ->
            scanList.addAll(filteredDevices)

            if (scanList.size>0) {
                val data = scanList.distinct()
                val smoothPosition = data.size-1
                if (smoothPosition >=0 && smoothPosition < searchAdapter.itemCount) {
                    rvSearch.smoothScrollToPosition(smoothPosition)
                }
                searchAdapter.updateDevices(data)
            }
        }

        // 设置已配对设备回调
        bluetoothManager.setPairedCallback { pairedDevices ->

            runOnUiThread {
                pairedDevicesAdapter.updateDevices(pairedDevices)
            }
        }

        Handler(Looper.getMainLooper()).postDelayed(kotlinx.coroutines.Runnable {
            // 注册回调
            bluetoothManager.registerCallback(connectionCallback)

            // 初始化蓝牙管理器
            bluetoothManager.fetchPairedDevices()

            // 检查蓝牙状态并更新UI
            updateBluetoothState(bluetoothManager.getBluetoothState())

            if (bluetoothManager.getBluetoothState() == BluetoothAdapter.STATE_ON) {
                bluetoothManager.startScan()
            }

            CoroutineScope(Dispatchers.IO).launch {

                val allreadyConnectd  = bluetoothManager.isInitDeviceConnected()

                if (!TextUtils.isEmpty(allreadyConnectd)) {
                    withContext(Dispatchers.Main) {
                        tvConnectStat.text= allreadyConnectd
                    }
                }

            }

        }, 1000)
    }

    override fun onResume() {
        super.onResume()
        updateBluetoothState(bluetoothManager.getBluetoothState())
    }

    override fun getLayoutId(): Int {
        return R.layout.activiyt_bluetooth
    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    override fun onDestroy() {
        super.onDestroy()
        bluetoothManager.unregisterCallback(connectionCallback)
        bluetoothManager.stopScan()
        unregisterReceiver(bluetoothReceiver)
    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENABLE_BT && resultCode == RESULT_OK) {
            bluetoothManager.startScan()
        }
    }

    // 刷新蓝牙
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    private fun refreshBluetooth() {
        if (bluetoothManager.getBluetoothState() == BluetoothAdapter.STATE_ON) {
            bluetoothManager.startScan()
        } else {
            switcher.setCheckedState(false)
            CentreToast.instance.showText("请先启用蓝牙")
        }
    }

    // 更新蓝牙状态UI
    private fun updateBluetoothState(state: Int) {
        when (state) {
            BluetoothAdapter.STATE_ON -> switcher.setCheckedState(true)
            BluetoothAdapter.STATE_OFF -> {
                switcher.setCheckedState(false)
                scanList.clear()
                searchAdapter.updateDevices(scanList)
            }
        }
    }

}